import React, { useEffect, useRef, useState, forwardRef, useImperativeHandle } from 'react';
import * as echarts from 'echarts';
import { ColorPicker, Flex, Button } from 'antd';
import { useTranslation } from 'react-i18next';
import domtoimage from 'dom-to-image';

let chart = null;
const BarChart = forwardRef(({ chartsData, zoomRatio }, ref) => {
  const { t } = useTranslation();
  const chartRef = useRef(null);
  // const [copyChartsData, setCopyChartsData] = useState([]);

  // let legend = chartsData && chartsData?.map((item) => {
  //   return item.name;
  // }) || [];
  // 雷达图默认颜色
  const CHART_COLOR = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'];
  const [colorList, setColorList] = useState(CHART_COLOR);
  const [legend, setLegend] = useState([]);
  const [legendVisable, setLegendVisable] = useState({});

  // 汇总并去重 indicators
  let indicatorList = [...new Set(chartsData?.map(item => item?.indicator)?.flat())];
  // 根据维度汇总数据
  const chartsDataByIndicator = indicatorList?.map((val, valIndex) => {
    return {
      indicator: val,
      indicatorIndex: valIndex,
      data: chartsData?.map((item, index) => {
        const colorIndex = index % colorList.length;
        const valueIndex = item?.indicator?.findIndex((i) => i === val);
        const keyNewValue = item?.value?.[valueIndex] || '-';
        return {
          name: item?.name,
          value: keyNewValue,
          color: colorList[colorIndex],
        }
      })
    };
  });
  const options = {
    color: colorList,
    legend: {
      show: false,
      selected: {
        // item: false
      },
      triggerEvent: true,
      tooltip: {
        trigger: 'item',
        textStyle: {
          align: 'left' // 左对齐
        },
      },
    },
    radar: {
      radius: '80%',
      indicator: chartsData && chartsData?.[0]?.indicator?.map((item) => {
        return {
          name: item || ''
        }
      }) || [],
      nameGap: 8,
      triggerEvent: true,
      tooltip: {
        trigger: 'axis',
        formatter: function (params) {
          const itemIndicatorName = params?.name;
          const tooltipData = {
            data: chartsDataByIndicator?.filter(item => item?.indicator === itemIndicatorName)?.[0]?.data || [],
            itemIndicator: itemIndicatorName,
          };
          const itemListHtml = tooltipData?.data?.map((item) => `
            <div class='item'>
            <span class='item-mark' style='background:${item?.color}'></span>
            <span class='item-name'>${item?.name}</span>
            <span class='item-value'>${item?.value}</span>
            </div>
          `).join('');
          const indicatorDataHtml = `<div class="radar-tooltip-wrap">
            <div class='series-name'>${tooltipData?.itemIndicator}</div>
              ${itemListHtml}
          </div>`;
          return indicatorDataHtml;
        },
      },
    },
    tooltip: {
      trigger: 'item',
      confine: true,
    },
    series: [
      {
        type: 'radar',
        data: chartsData && chartsData?.map((item) => {
          return {
            value: item?.value || [],
            name: item?.name || ''
          }
        }) || [],
      }
    ],
    grid: {
      containLabel: true
    },
  };
  // 更改雷达图颜色
  const colorChangeHandle = (val, index) => {
    const newColorList = [...colorList];
    newColorList[index] = val.toHexString();
    setColorList(newColorList);
    chart.setOption({
      ...options,
      color: newColorList
    });
  };
  // 显示隐藏某条数据
  const legendClick = (item) => {
    const newLegendVisable = { ...legendVisable };
    newLegendVisable[item] = newLegendVisable[item] === true ? false : true;
    setLegendVisable(newLegendVisable);
    chart.setOption({
      ...options,
      legend: {
        ...legend,
        selected: newLegendVisable
      }
    });
  };

  const chartResize = (delay = 100) => {
    setTimeout(() => {
      try {
        const renderChartInstance = echarts.getInstanceByDom(chartRef.current);
        if (renderChartInstance) {
          chart = renderChartInstance;
        } else {
          chart = echarts.init(chartRef.current);
        }
        chart.resize();
      } catch (error) {
        chart && chart?.dispose();
      };
    }, delay);
  };
  // 导出图片
  const chartsExportImg = async () => {
    const blob = await new Promise((resolve) => {
      domtoimage.toBlob(document.getElementById('radar-chart')).then((blob) => {
        resolve(blob);
      });
    });
    const file = new File([blob], "chart.png", { type: 'image/png' });
    console.log(file);
    return file;
  };
  useImperativeHandle(ref, () => ({
    chartsExportImg,
  }));

  const legendUpdateFn = () => {
    const legendData = chartsData && chartsData?.map((item) => {
      return item.name;
    }) || [];
    setLegend(legendData);
    setLegendVisable(legendData?.reduce((total, currVaL) => {
      total[currVaL] = true;
      return total;
    }, {}));
  };

  // 根据维度汇总数据，补充缺失维度
  // const copyFormatChartsData = () => {
  //   console.log("indicatorList", indicatorList);
  //   const chartsDataByIndicator = indicatorList?.map((val, valIndex) => {
  //     return {
  //       indicator: val,
  //       indicatorIndex: valIndex,
  //       data: chartsData?.map((item, index) => {
  //         const valueIndex = item?.indicator?.findIndex((i) => i === val);
  //         const keyNewValue = item?.value?.[valueIndex] || null;
  //         return {
  //           name: item?.name,
  //           value: keyNewValue,
  //         }
  //       })
  //     };
  //   });
  //   console.log("chartsData", chartsData);
  //   console.log("chartsDataByIndicator", chartsDataByIndicator);
  //   setCopyChartsData(chartsDataByIndicator);
  // };

  useEffect(() => {
    legendUpdateFn();
    chartResize();
  }, [zoomRatio]);
  useEffect(() => {
    legendUpdateFn();
    chart = echarts.init(chartRef.current);
    chart.setOption(options);
    window.addEventListener('resize', () => { chartResize() });
    return () => {
      window.removeEventListener('resize', () => { chartResize() });
      chart.dispose();
    };
  }, [chartsData]);

  return (
    <>
      {
        legend &&
        <div className='radar-wrap' style={{ width: '100%', height: '90%' }} id='radar-chart'>
          <Flex align='center' style={{ flexWrap: 'wrap' }}>
            {
              legend?.map((item, index) => {
                const colorIndex = index % colorList.length;
                return (
                  <Flex align='center'>
                    <Button className='legend-btn' type='link' size='mini' style={{ color: legendVisable?.[item] === true ? '#333333' : '#999999' }} onClick={() => legendClick(item)}>{item} </Button>
                    <div className='color-picker-btn'>
                      <ColorPicker
                        value={colorList?.[colorIndex]}
                        onChangeComplete={(val) => { colorChangeHandle(val, index) }}
                      />
                    </div>
                  </Flex>
                )
              })
            }
          </Flex>
          {
            chartsData?.length === 0 &&
            <div className='chart-no-data'>{t('common.noData')}</div>
          }
          <div ref={chartRef} style={{ width: '100%', height: '100%', borderRadius: '8px', backgroundColor: '#FFFFFF' }} />
        </div>
      }
    </>
  )
});

export default BarChart;
